<?php

class System_Api_Local
{
    private $_apiService = array();

    public function __construct($apiService = array())
    {
        $this->_apiService = $apiService;
    }

    public function getMethod($method)
    {
        // method $apiService['social.user.login'] = array('Social_User', 'login');
        if(isset($this->_apiService[$method])) {
            return $this->_apiService[$method];
        } else {
            throw new Exception('Call undefined method: ' . $method);
        }
    }

    public function call($method, $params = array())
    {
        $apiMethod = $this->getMethod($method);
        $className = isset($apiMethod['class']) ? $apiMethod['class'] : '';
        if(!class_exists($className)) {
            throw new Exception('Service class was not found: ' . $className);
        }
        $methodName = isset($apiMethod['method']) ? $apiMethod['method'] : '';
        if(empty($methodName)) {
            throw new Exception('Service method was not defined');
        }

        $callParams = array();
        if(!isset($apiMethod['params'])) {
            $apiParams = array();
        } else {
            $apiParams = $apiMethod['params'];
        }
        foreach($apiParams as $apiParam) {
            $field = trim($apiParam);
            $callParams[] = isset($params[$field]) ? trim($params[$field]) : null;
        }
        $class = new $className();
        return call_user_func_array(array($class, $methodName), $callParams);
    }

}
